package org.ezplatform.goa.document.service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

import org.apache.commons.collections.CollectionUtils;
import org.ezplatform.cloud.api.bpm.BpmApiService;
import org.ezplatform.cloud.common.client.RestClient;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.pagination.ExtPageRequest;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.goa.document.entity.DocSignreport;
import org.ezplatform.goa.document.entity.GovDistPartnumber;
import org.ezplatform.goa.document.entity.GovDocReceiveFile;
import org.ezplatform.goa.document.entity.GovSendFile;
import org.ezplatform.goa.document.util.DocumentSecUtils;
import org.ezplatform.goa.document.util.GoaCommonUtils;
import org.ezplatform.goa.document.web.rest.GovDealListPortletController;
import org.ezplatform.office.portlet.common.service.PortletService;
import org.ezplatform.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;

@Service("GovDealListPortalService")
@Transactional
public class GovDealListPortalService extends BaseService{

	private final Logger logger = LoggerFactory.getLogger(GovDealListPortalService.class);

	@Autowired
	private GovDistributeUserService disService;
	
	@Autowired
	private GovDistributeRecordService govDistributeRecordService;
	
	@Autowired
	private GovFlowBackService govFlowBackService;
	
	@Autowired
	private GovSendFileService sendFileService;

	@Autowired
	private GovDocReceiveFileService receiveFileService;
	
	@Autowired
	private DocSignreportService signReportService;
	
	@Autowired
	private RestClient restClient;
	
	@Autowired
	public GovMyAttentionService myAttentionService;
	
	@Autowired
	protected PortletService portletService;

	@Autowired
	private GovDistributeRecordService disRecordService;

	@Autowired
	private DocumentSecUtils documentSecUtils;

    @Autowired
    private BpmApiService bpmApiService;

	@Autowired
	private GoaCommonUtils goaCommonUtils;

	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	@Override
	protected JpaBaseDao<GovDistPartnumber, String> getEntityDao() {
		return null;
	}
	
	/**
	 * 获取
	 * @param module
	 * @param limit
	 * @param showDateFormat
	 * @param showItemSet
	 * @return
	 * @throws ExecutionException 
	 * @throws InterruptedException 
	 */
	public List<Map> getProcessDataList(String[] moduleArr, String limit, String showDateFormat, String showItemSet,WebUser user,String currentModule) throws InterruptedException, ExecutionException {
		/*List<Map> listMap = new ArrayList<Map>();
		List<Callable<Map>> taskList = Lists.newArrayList();
		int limitSize = Integer.parseInt(limit);
		for (String module : moduleArr) {
		  if("0".equals(module)) {//待办发文
			  Callable<Map> undoSendList = () -> getUndoSendList(user,limitSize,showDateFormat);
			  taskList.add(undoSendList);
		  }else if("1".equals(module)) {//待办收文
			  Callable<Map> undoReceiveList = () -> getUndoReceiveList(user,limitSize,showDateFormat);
			  taskList.add(undoReceiveList);
		  }else if("2".equals(module)) {//待办签报
			  Callable<Map> undoSignList = () -> getUndoSignList(user,limitSize,showDateFormat);
			  taskList.add(undoSignList);
		  }
		  else {//以及其它8只
			  
		  }
		}
		 GovThreadExecutor myThreadExecutor = new GovThreadExecutor();
		 List<Map> dealResult = myThreadExecutor.invokeAll(taskList);
		 return dealResult;*/
		return null;
	}

	/**
	 * 门户-公文办理列表-待办发文列表
	 * @param user 
	 * @param limitSize 
	 * @return
	 */
	private Map getUndoSendList(WebUser user, int limitSize,String showDateFormat) {
		Map resultMap  =  getUndoList(user, "goa_doc_sendfile", limitSize, "待办发文", showDateFormat);
		return resultMap;
	}
	
	/**
	 * 门户-公文办理列表-待办收文列表
	 * @param user 
	 * @param limitSize 
	 * @return
	 */
	private Map getUndoReceiveList(WebUser user, int limitSize,String showDateFormat) {
		Map resultMap  =  getUndoList(user, "goa_doc_receivefile", limitSize, "待办收文", showDateFormat);
		return resultMap;
	}
	
	/**
	 * 门户-公文办理列表-待办签报列表
	 * @param user 
	 * @param limitSize 
	 * @return
	 */
	private Map getUndoSignList(WebUser user, int limitSize,String showDateFormat) {
		Map resultMap  =  getUndoList(user, "goa_doc_signreport", limitSize, "待办签报", showDateFormat);
		return resultMap;
	}
	
	/**
	 * 门户-公文办理列表-待办列表
	 * @param user
	 * @param category
	 * @param limitSize
	 * @param moduleName
	 * @param showDateFormat
	 * @return
	 */
	public Map getUndoList(WebUser user, String category, int limitSize,String moduleName,String showDateFormat) {
		Map resultMap  =  new HashMap(); 
		List<Map> list = new ArrayList<>();
		List todayList = new ArrayList<>();
		List yesterdayList = new ArrayList<>();
		List thisWeekList = new ArrayList<>();
		List moreList = new ArrayList<>();
		Map userParams = new HashMap();
		userParams.put("userId", user.getUserId());
		userParams.put("corpId", user.getCorpId());
		userParams.put("index", "0");
		userParams.put("limit", limitSize);
		userParams.put("category", category);
		userParams.put("module", "goa_document");
		userParams.put("from", "pendingList");
		userParams.put("groupId", user.getCurrentPtOrgId());
		String json = bpmApiService.getUndoTaskList(userParams,user.getJwtToken());
		Map jsonMap = JsonUtils.readValue(json);
		Map data = (Map) jsonMap.get("data");
		list = (List) data.get("list");
		for (Map m : list) {
			// 今天或昨天
			if(isToday(m.get("createTime")+"")) {
				todayList.add(m);
			}else if(isYesterday(m.get("createTime")+"")) {
				yesterdayList.add(m);
			}
			// 非本周即更多
			if(isThisWeek(m.get("createTime")+"")) {
				thisWeekList.add(m);
			}else {
				moreList.add(m);
			}
			String createTime = StringUtils.null2String(m.get("createTime"));
			if (StringUtils.isNotEmpty(createTime)) {
				createTime = DateUtils.formatDate(DateUtils.parseDate(createTime, "yyyy-MM-dd HH:mm:ss"), showDateFormat);
				m.put("createTime", createTime);
			}
			setLightType(m,"0");
		}
		resultMap.put("module", "0");
		resultMap.put("moduleName", moduleName);
		resultMap.put("listCount", list.size());
		resultMap.put("todayListCount", todayList.size());
		resultMap.put("yesterdayListCount", yesterdayList.size());
		resultMap.put("thisWeekListCount", thisWeekList.size());
		resultMap.put("moreListCount", moreList.size());
		if(list.size() > limitSize) {
			resultMap.put("list", list.subList(0, limitSize));
		}else {
			resultMap.put("list", list);
		}
		if(todayList.size() > limitSize) {
			resultMap.put("todayList", todayList.subList(0, limitSize));
		}else {
			resultMap.put("todayList", todayList);
		}
		if(yesterdayList.size() > limitSize) {
			resultMap.put("yesterdayList", yesterdayList.subList(0, limitSize));
		}else {
			resultMap.put("yesterdayList", yesterdayList);
		}
		if(thisWeekList.size() > limitSize) {
			resultMap.put("thisWeekList", thisWeekList.subList(0, limitSize));
		}else {
			resultMap.put("thisWeekList", thisWeekList);
		}
		if(moreList.size() > limitSize) {
			resultMap.put("moreList", moreList.subList(0, limitSize));
		}else {
			resultMap.put("moreList", moreList);
		}
		return resultMap;
	}
	
	
	
	/**
	 * 
	 * @param moduleArr
	 * @param showNumber
	 * @param showDateFormat
	 * @param showItemSet
	 * @param user
	 * @return
	 * @throws ExecutionException 
	 * @throws InterruptedException 
	 */
	public List<Map> getProcessList(String[] moduleArr, String showNumber, String showDateFormat, String showItemSet,
			WebUser user,String currentModule) throws InterruptedException, ExecutionException {
		List<Map> list  =  new ArrayList<Map>();
		for (String module : moduleArr) {
			 Map  map  =  getMapByProcess(showNumber,module,showDateFormat,user,showItemSet,currentModule);
			 list.add(map);
		}
		list = documentSecUtils.documentListEncodeListById(list);
		return list;
	}

	/**
	 * 获取流程基础设置
	 */
	public Map getBpmProcessBasic(String token) {
		Map data = new HashMap();
		try{
			Map<String, String> params = new HashMap<String, String>();
			String json = bpmApiService.getBpmProcessBasic(params, token);
			Map<String, Object> jsonMap = JsonUtils.readValue(json);
			if(jsonMap!=null && jsonMap.size()>0 && StringUtils.equals(StringUtils.null2String(jsonMap.get("code")),"0")){
				data = (Map)jsonMap.get("data");
			}
		}catch(Exception e){
			logger.error("获取流程基础设置 报错：",e);
		}
		return data;
	}

	/**
	 * 
	 * @param module
	 * @param limit
	 * @return
	 */
	private Map getRestList(String limit,String module) {
		Map resultMap = new HashMap();
        WebUser user = WebUtils.getCurrentUser();
        String token = user.getJwtToken();
		Map<String,String> paramMap = new HashMap<String,String>();
		paramMap.put("limit", limit);
		paramMap.put("index", "0");
		paramMap.put("module", "goa_document");
		paramMap.put("from", "govdoc");
		paramMap.put("userId",user.getUserId());
		paramMap.put("corpId",user.getCorpId());
		//是否涉密开启
        Boolean secretFlag = GlobalConstant.isUseSecretLevel();
        String secretLevel = "";
        if(secretFlag) {
        	//获取当前登录人的涉密登记
            secretLevel = String.valueOf(user.getSecretLevel());
            Map userParams = new HashMap();
    		userParams.put("secretLevel", secretLevel);
    		paramMap.put("searchData", JsonUtils.writeValueAsString(userParams));      
        }
        String json = "";
        if("0".equals(module)) {
            json = bpmApiService.getUndoTaskList(paramMap,token);
        }else if("2".equals(module)) {
            json = bpmApiService.getDoneProcessList(paramMap,token);
        }else if("4".equals(module)) {
            json = bpmApiService.getMyProcessList(paramMap,token);
        }else if("d".equals(module)) {
			paramMap.put("category","goa_doc_sendfile");
			json = bpmApiService.getUndoTaskList(paramMap,token);
		}else if("e".equals(module)) {
			paramMap.put("category","goa_doc_receivefile");
			json = bpmApiService.getUndoTaskList(paramMap,token);
		}
        if (StringUtils.isNotBlank(json)) {
            resultMap = JsonUtils.readValue(json);
        }
		Map<String, Object> data = (Map<String, Object>) resultMap.get("data");
		List tempList = Arrays.asList(data.get("list"));
		List<Map>  newList = (List<Map>) tempList.get(0);
		newList = DocumentSecUtils.approveListEncodeList(newList,"processInstanceId,id","");
		tempList = (List) newList;
		//对list进行处理
		if("0".equals(module)) {
			//如果是待办列表，根据后台设置来。
			Map processBasic = getBpmProcessBasic(token);
			//紧急程度集
			List<Map<String,String>> emergencyList = goaCommonUtils.getEmergencyDegree();
			//办理缓急-使用同一个结果集
			List<Map<String,String>> blhjList = goaCommonUtils.getEmergencyDegree();
			Map<String,String> blhjMap = buildBlhjMap(blhjList);
			String undoShowField  = "4";//默认使用紧急程度
			if(!processBasic.isEmpty()){
				undoShowField = processBasic.get("undoShowField")!=null?processBasic.get("undoShowField").toString():"";
			}
			String undoShowFieldvalue = "";
			for(int i=0;i<tempList.size();i++){
				Map resultMap1 = (Map)tempList.get(i);
				String  extUrgentField = resultMap1.get("extUrgentField")!=null?resultMap1.get("extUrgentField").toString():"";
				String  taskUrgent = resultMap1.get("taskUrgent")!=null?resultMap1.get("taskUrgent").toString():"";
				//办理缓急
				if(undoShowField.indexOf("4")>-1){
					resultMap1.put("taskUrgent",blhjMap.get(taskUrgent));
					undoShowFieldvalue = "4";
				}
				//紧急程度
				else if(undoShowField.indexOf("3")>-1){
					resultMap1.put("extUrgentField",extUrgentField);
					undoShowFieldvalue = "3";
				}
				resultMap1.put("undoShowField",undoShowFieldvalue);

				String extWorkStatus = StringUtils.null2String(resultMap1.get("extWorkStatus"));//待呈-1、领导批示-2、领导退回-3
				String extWorkStatusShow = "";
				if(StringUtils.isNotBlank(extWorkStatus)){
					extWorkStatusShow = extWorkStatus.equals("1")?"(待呈)":(extWorkStatus.equals("2")?"(领导批示)":(extWorkStatus.equals("3")?"(领导退回)":""));
				}
				resultMap1.put("extWorkStatusShow",extWorkStatusShow);
			}
		}
		data.put("list",tempList);
		resultMap.put("data",data);
		return resultMap;
	}

	/**
	 * 构建办理缓急结果集
	 * @param blhjList
	 * @return
	 */
	private Map<String, String> buildBlhjMap(List<Map<String, String>> blhjList) {
		Map resutMap = new HashMap();
		for (int i=0;i<blhjList.size();i++){
			Map blhjMap = blhjList.get(i);
			resutMap.put(blhjMap.get("code"),blhjMap.get("name"));
		}
		return resutMap;
	}


	/**
	 * @SuppressWarnings("all")
	 * @param user
	 * @param limitSize
	 * @param showDateFormat
	 * @param user 
	 * @param showItemSet 
	 * @return
	 */
	@SuppressWarnings("all")
	public Map getMapByProcess(String limit,String module ,String showDateFormat, WebUser user, String showItemSet, String currentModule) {
		Map result = new HashMap();
		Map resultMap = new HashMap();
		//处理固定基本信息
		dealResultMap(module,resultMap);
		boolean flag = true ;
		if(currentModule.indexOf(module)==-1) {
			flag = false;
		}
		if("1".equals(module)) {
			if(currentModule.indexOf("1")==0) {
				result = getListByPortlet("0", "unread",limit);
			}else {
				result = getListByPortletNum();
				if ("0".equals(StringUtils.null2String(result.get("code")))) {
					Map data = (Map) result.get("data");
					List listInfo = new ArrayList<>();
					listInfo = (List) data.get("list");
					resultMap.put("totalNum", data.get("totalNum"));
				}
				flag = false;
			}
		}else if("3".equals(module)&&flag) {
			result = getListByPortlet("0", "readed",limit);
		}else if("5".equals(module)&&flag) {
			result = getDisListByPortlet(limit);
		}else if("6".equals(module)&&flag) {
			result = getMyAttentionListByPortlet(limit);
		}else if("7".equals(module)&&flag) {
			result = getFlowBackListByPortlet(limit);
		}else if("8".equals(module)) {
			if(currentModule.indexOf("8")==0) {
				result = getDocWaitingReadFileRecv("2", "unread",limit);
			}else {
				result = getDocWaitingReadFileRecv("2", "unread",limit);
				if ("0".equals(StringUtils.null2String(result.get("code")))) {
					Map data = (Map) result.get("data");
					List listInfo = new ArrayList<>();
					listInfo = (List) data.get("list");
					resultMap.put("totalNum", data.get("totalNum"));
				}
				flag = false;
			}
		}else if("9".equals(module)) {
			if(currentModule.indexOf("9")==0) {
				result = getDocWaitingReadFileRecv("3", "unread",limit);
			}else {
				result = getDocWaitingReadFileRecv("3", "unread",limit);
				if ("0".equals(StringUtils.null2String(result.get("code")))) {
					Map data = (Map) result.get("data");
					List listInfo = new ArrayList<>();
					listInfo = (List) data.get("list");
					resultMap.put("totalNum", data.get("totalNum"));
				}
				flag = false;
			}
		}else if("a".equals(module)&&flag) {
			result = getRegisterByPortlet(limit);
		}else if("b".equals(module)&&flag) {//已归档
			result = getArchive("1", limit);
		}else if("c".equals(module)&&flag) {//待归档
			result = getArchive("0", limit);
		}else if("0".equals(module)&&flag) {
			result = getRestList(limit,module);
		}else if("2".equals(module)&&flag) {
			result = getRestList(limit,module);
		}else if("4".equals(module)&&flag) {
			result = getRestList(limit,module);
		}else if("d".equals(module)) {
			flag = true;
			result = getRestList(limit,module);
		}else if("e".equals(module)) {
			flag = true;
			result = getRestList(limit,module);
		}
		//对查询的list数据进行处理
		if(flag){
			dealResultList(resultMap,result,module,showDateFormat,user,showItemSet,flag);
		}
		return resultMap;
	}

	/**
	 * 处理当前以及上一环节办理人
	 * @param resultMap
	 * @param result
	 * @param module
	 * @param showDateFormat
	 * @param user
	 * @param info
	 * @param showItemSet
	 */
	@SuppressWarnings("all")
	private void dealCurrentOrUpInfo(Map resultMap, Map result, String module, String showDateFormat, WebUser user, Map info, String showItemSet,boolean falg) {
		if(!"1".equals(module) && !"3".equals(module) && !"5".equals(module)) {
			Map paramMap2 = new HashMap();
			paramMap2.put("userId", user.getUserId());
			paramMap2.put("corpId", user.getCorpId());
			paramMap2.put("processInstanceId", info.get("processInstanceId"));
			//查询当前环节办理人，上一环节办理人
			if("0".equals(module)&&(falg == true) && showItemSet.indexOf("preName")>-1) {//待办列表
				/*if(showItemSet.contains("currentName")) {
					paramMap2.put("taskId", info.get("id"));
					String json = this.restClient.get("/bpm/runtime/getProcessInfo", user.getJwtToken(), paramMap2);
					Map m = JsonUtils.readValue(json);
					Map data2 = (Map) m.get("data");
					String currentName = StringUtils.EMPTY;
					if(data2 !=null) {
						 currentName = StringUtils.null2String(data2.get("undoUsers"));
					}
					if(StringUtils.isNotEmpty(currentName)) {
						info.put("currentName", currentName);
					}
				}*/
				if(showItemSet.contains("preStatus") || showItemSet.contains("preName")) {
					paramMap2.put("taskId", info.get("id"));
					String json2 = bpmApiService.getLastNodeUserInfo(paramMap2,user.getJwtToken());
					Map m2 = JsonUtils.readValue(json2);
					Map data3 = (Map) m2.get("data");
					String preStatus = StringUtils.EMPTY;
					String preName = StringUtils.EMPTY;
					if(data3 !=null) {
						preStatus = StringUtils.null2String(data3.get("nodeName"));
						preName = StringUtils.null2String(data3.get("userName")); 
					}
					if(StringUtils.isNotEmpty(preStatus)) info.put("preStatus", preStatus);
					if(StringUtils.isNotEmpty(preName)) info.put("preName", preName);
				}
			}else {
				//6 我的关注 7我的退回,不查询上一环节的情况
				//只有待办查询上一环节办理人，其他模块先不查询。
				if(("2".equals(module)|| ("4".equals(module))) &&(falg == true)) {
					info.put("currentName", info.get("curUserName"));
					/*if(showItemSet.contains("preStatus") || showItemSet.contains("preName")) {
						String json = this.restClient.get("/bpm/runtime/getLastNodeInfo", user.getJwtToken(), paramMap2);				
						Map m = JsonUtils.readValue(json);
						List list = (List) m.get("data");
						Map data2 = CollectionUtils.isNotEmpty(list) ? (Map)list.get(0) : null;
						String preStatus = StringUtils.EMPTY;
						String preName = StringUtils.EMPTY;
						if(data2 !=null) {
							preStatus = StringUtils.null2String(data2.get("nodeName"));
							preName = StringUtils.null2String(data2.get("userName"));
						}
						if(StringUtils.isNotEmpty(preStatus)) info.put("preStatus", preStatus);
						if(StringUtils.isNotEmpty(preName)) info.put("preName", preName);
					}*/
				}else if(("6".equals(module)|| ("7".equals(module)))&&(falg == true)) {
					String json = bpmApiService.getProcessTrackInfo(paramMap2,"",user.getJwtToken());
					Map m = JsonUtils.readValue(json);
					Map data2 = (Map) m.get("data");
					if (data2 != null){
						List<Map> mapList = (List<Map>)data2.get("activityList");
						// 获取当前办理人
						if(mapList != null && mapList.size() > 0) {
							Map map2 = mapList.get(mapList.size() -1);
							String currentName = "";
							List<Map> assigneeList =(List<Map>) map2.get("assigneeList");
							if(assigneeList!=null && !assigneeList.isEmpty() && assigneeList.size() > 0) {
								for (Map map3 : assigneeList) {
									String assigneeName = "$" + map3.get("name") + "$";
									if(!currentName.contains(assigneeName)) {
										currentName += assigneeName+",";
									}
								}
									if(currentName.length() > 0) {
										currentName = currentName.substring(0, currentName.length() -1);
										currentName = currentName.replaceAll("\\$", "");
									}
								}
								info.put("currentName", currentName);
							}
						}
					//我的退回当前办理人为空时数据处理
                    if (("7".equals(module))&&(falg == true)) {
                        String currentName = info.get("currentName") == null ? "" : StringUtils.null2String(info.get("currentName"));
                        if (StringUtils.isBlank(currentName)) {
                            info.put("currentName", info.get("backUser"));
                        }
                    }
					}
				}
			}
		}

	/**
	 * 对查询的list数据进行处理
	 * @param resultMap
	 * @param result
	 * @param module
	 * @param showDateFormat
	 * @param user
	 * @param showItemSet
	 */
	private void dealResultList(Map resultMap, Map result, String module, String showDateFormat, WebUser user,String showItemSet,boolean falg) {
		if ("0".equals(StringUtils.null2String(result.get("code")))) {
			Map data = (Map) result.get("data");
			List listInfo = new ArrayList<>();
			listInfo = (List) data.get("list");

			if("0".equals(module)) {
				resultMap.put("totalNum", data.get("count"));
			}
			if("1".equals(module)) {
				resultMap.put("totalNum", data.get("totalNum"));
			}
			if("8".equals(module)) {
				resultMap.put("totalNum", data.get("totalNum"));
			}
			if("9".equals(module)) {
				resultMap.put("totalNum", data.get("totalNum"));
			}
			if("d".equals(module)) {
				resultMap.put("totalNum", data.get("count"));
			}
			if("e".equals(module)) {
				resultMap.put("totalNum", data.get("count"));
			}
			for (int j = 0; j < listInfo.size(); j++) {
				Map info = (Map) listInfo.get(j);
				//处理基础信息
				dealResultInfoList(resultMap,result,module,showDateFormat,user,info,falg);
				//处理当前环节办理人以及上一环节办理人
				dealCurrentOrUpInfo(resultMap,result,module,showDateFormat,user,info,showItemSet,falg);
			}
			resultMap.put("listInfo", listInfo);
		}
	}

	/**
	 * 处理list信息
	 * @param resultMap
	 * @param result
	 * @param module
	 * @param showDateFormat
	 * @param user
	 * @param info
	 */
	private void dealResultInfoList(Map resultMap, Map result, String module, String showDateFormat, WebUser user, Map info,boolean falg) {
		String createTime = StringUtils.null2String(info.get("createTime"));
		if (StringUtils.isNotEmpty(createTime)) {
			createTime = DateUtils.formatDate(DateUtils.parseDate(createTime, "yyyy-MM-dd HH:mm:ss"), showDateFormat);
			info.put("createTime", createTime);
		}
		if(("0".equals(module)||"d".equals(module)||"e".equals(module))&&(falg == true)) {
			info.put("curStepName", info.get("name"));
            if (info.get("startUserGroupNameFull") != null) {
                info.put("startUserGroupName", info.get("startUserGroupNameFull"));
            }
			// 判断文件灯、个人灯
			setLightType(info,module);
		}else if("2".equals(module)&&(falg == true)) {
			String dealTime = StringUtils.null2String(info.get("dealTime"));
			if (StringUtils.isNotEmpty(dealTime)) {
				dealTime = DateUtils.formatDate(DateUtils.parseDate(dealTime, "yyyy-MM-dd HH:mm:ss"), showDateFormat);
				info.put("createTime", dealTime);
			}
			if(info.get("curStepName") == null) {
				info.put("curStepName", "结束");
			}
			info.put("id", info.get("taskId"));
			setLightType(info,module);
		}else if(("1".equals(module) || "3".equals(module))&&(falg == true)) {//待阅，已阅列表
			createTime = StringUtils.null2String(info.get("createddate"));
			if("3".equals(module)) {
				createTime = StringUtils.null2String(info.get("finishdate"));
			}else {
				String readStatus = info.get("read_status")+"";
				if("1".equals(readStatus)) {
					info.put("claimTime", readStatus);
				}else {
					info.put("claimTime", null);
				}
			}
			if (StringUtils.isNotEmpty(createTime)) {
				createTime = DateUtils.formatDate(DateUtils.parseDate(createTime, "yyyy-MM-dd HH:mm:ss"), showDateFormat);
			}
			info.put("createTime", createTime);
			info.put("formKey", info.get("form_id"));
			info.put("processInstanceId", info.get("process_instance_id"));
			info.put("businessKey", info.get("business_id"));
			info.put("title", info.get("dis_title"));
			info.put("startUserName", info.get("dis_user_name"));
			//info.put("startUserGroupName", info.get("dis_org_name"));
			if (info.get("startUserGroupName") != null) {
				info.put("startUserGroupName", info.get("startUserGroupName"));
			}
			info.put("curStepName", info.get(""));
		}else if("4".equals(module)&&(falg == true)) { //我的发起列表
			 String id = StringUtils.null2String(info.get("businessKey"));
			 String category = StringUtils.null2String(info.get("category"));
			 if(StringUtils.isNoneBlank(id) && "goa_doc_sendfile".equals(category)) {
				 GovSendFile sendfile = sendFileService.findOne(id);
				 if(sendfile != null) {
					 info.put("flowStatus", sendfile.getFlowStatus());
				 }
			 }else if(StringUtils.isNoneBlank(id) && "goa_doc_receivefile".equals(category)) {
				 GovDocReceiveFile receivefile = receiveFileService.findOne(id);
				 if(receivefile != null) {
					 info.put("flowStatus", receivefile.getFlowStatus());	
				 }
			 }else if(StringUtils.isNoneBlank(id) && "goa_doc_signreport".equals(category)) {
				 DocSignreport signReportFile = signReportService.findOne(id);
				 if(signReportFile != null) {
					 info.put("flowStatus", signReportFile.getFlowStatus());
	             }
			 }
			 if("2".equals(info.get("flowStatus"))) {
				 info.put("curStepName", "结束");
			 }else if("3".equals(info.get("flowStatus"))) {
				 info.put("curStepName", "取消");
			 }else if("4".equals(info.get("flowStatus"))) {
				 info.put("curStepName", "作废");
			 }else if("5".equals(info.get("flowStatus"))) {
				 info.put("curStepName", "退回");
			 }
			 //info.put("startUserGroupName", user.getOrgName());
			if (info.get("startUserGroupNameFull") != null) {
				info.put("startUserGroupName", info.get("startUserGroupNameFull"));
			}
			 setLightType(info,module);
		}else if("5".equals(module)&&(falg == true)) {//我的分发
			createTime = StringUtils.null2String(info.get("sendTime_selfsend"));
			if (StringUtils.isNotEmpty(createTime)) {
				createTime = DateUtils.formatDate(DateUtils.parseDate(createTime, "yyyy-MM-dd HH:mm:ss"), showDateFormat);
			}
			info.put("createTime", createTime);
			info.put("processInstanceId", info.get("process_instance_id"));
			info.put("title", info.get("send_title"));
			//info.put("startUserGroupName", info.get("starFlowtUnit"));
			if (info.get("startUserGroupName") != null) {
				info.put("startUserGroupName", info.get("startUserGroupName"));
			}
			info.put("startUserName", info.get("starFlowtUser"));
			info.put("formKey", info.get("form_id"));
			info.put("businessKey", info.get("business_id"));
			info.put("category", info.get("source_category"));
			info.put("item_id", info.get("id"));
			info.put("id", info.get("task_id"));
		}else if("6".equals(module)&&(falg == true)) { //我的关注
			createTime = StringUtils.null2String(info.get("attentionTime"));
			if (StringUtils.isNotEmpty(createTime)) {
				if(createTime.length() == 10) {
					createTime = createTime + " 00:00:00";
				}
				Date parseDate = DateUtils.parseDate(createTime, "yyyy-MM-dd HH:mm:ss");
				createTime = DateUtils.formatDate(parseDate, showDateFormat);
			}
			info.put("title",info.get("title"));
			info.put("createTime", createTime);
			info.put("startUserGroupName", info.get("startUnit"));
            String dealUser = info.get("dealUser") == null ? "" : String.valueOf(info.get("dealUser"));
            if (StringUtils.isNotBlank(dealUser)) {
                info.put("startUserName", info.get("dealUser"));
            } else {
                info.put("startUserName", info.get("startUser"));
            }
			info.put("curStepName", info.get("dealStatus"));
			info.put("category", info.get("tableName"));
			info.put("formKey", info.get("form_key_"));
			// info.put("processInstanceId", info.get("followProcessId"));
			info.put("processInstanceId", info.get("proc_inst_id_"));
			info.put("businessKey", info.get("tableId"));
			info.put("id", info.get("id_"));
		}else if("7".equals(module)&&(falg == true)) {//我的退回
			createTime = StringUtils.null2String(info.get("backTime"));
			if (StringUtils.isNotEmpty(createTime)) {
				createTime = DateUtils.formatDate(DateUtils.parseDate(createTime, "yyyy-MM-dd HH:mm"), showDateFormat);
			}
			info.put("createTime", createTime);
			info.put("processInstanceId", info.get("process_instance_id"));
			//info.put("startUserGroupName", info.get("ext_startusergroupname"));
			if (info.get("startUserGroupName") != null) {
				info.put("startUserGroupName", info.get("startUserGroupName"));
			}
			info.put("startUserName", info.get("ext_startusername"));
			info.put("curStepName", info.get("dealstatus"));
			info.put("id", info.get("task_id"));
		}
	}

	private void dealResultMap(String module, Map map) {
		switch (module) {
			case "0":
				map.put("module", "0");
				map.put("moduleCode", "docWaitingDealFile");
				map.put("moduleName", "待办公文");
				map.put("editType", "edit");
				map.put("menuType", "pending");
				map.put("permissionCode", "pending");
				break;
			case "1":
				map.put("module", "1");
				map.put("moduleCode", "docWaitingReadFile");
				map.put("moduleName", "待阅公文");
				map.put("editType", "view");
				map.put("menuType", "unread");
				map.put("permissionCode", "pending");
				break;
			case "2":
				map.put("module", "2");
				map.put("moduleCode", "docDealFile");
				map.put("moduleName", "已办公文");
				map.put("editType", "view");
				map.put("menuType", "done");
				map.put("permissionCode", "done");
				break;
			case "3":
				map.put("module", "3");
				map.put("moduleCode", "docReadFile");
				map.put("moduleName", "已阅公文");
				map.put("editType", "view");
				map.put("menuType", "readed");
				map.put("permissionCode", "pending");
				break;
			case "4":
				map.put("module", "4");
				map.put("moduleCode", "myStart");
				map.put("moduleName", "我的发起");
				map.put("editType", "view");
				map.put("menuType", "my");
				map.put("permissionCode", "my");
				break;
			case "5":
				map.put("module", "5");
				map.put("moduleCode", "myDistribute");
				map.put("moduleName", "我的分发");
				map.put("editType", "view");
				map.put("menuType", "pending");
				map.put("permissionCode", "pending");
				break;
			case "6":
				map.put("module", "6");
				map.put("moduleCode", "myAttention");
				map.put("moduleName", "我的关注");
				map.put("editType", "view");
				map.put("menuType", "query");
				map.put("permissionCode", "pending");
				break;
			case "7":
				map.put("module", "7");
				map.put("moduleCode", "mySendback");
				map.put("moduleName", "我的退回");
				map.put("editType", "view");
				map.put("menuType", "pending");
				map.put("permissionCode", "pending");
				break;
			case "8":
				map.put("module", "8");
				map.put("moduleCode", "docWaitingReadFileRecv");
				map.put("moduleName", "待阅收文");
				map.put("editType", "view");
				map.put("menuType", "unread");
				map.put("permissionCode", "pending");
				break;
			case "9":
				map.put("module", "9");
				map.put("moduleCode", "docWaitingReadFileRead");
				map.put("moduleName", "待阅阅文");
				map.put("editType", "view");
				map.put("menuType", "unread");
				map.put("permissionCode", "pending");
				break;
			case "a":
				map.put("module", "a");
				map.put("moduleCode", "registerNoHandle");
				map.put("moduleName", "登记未处理");
				map.put("editType", "view");
				map.put("menuType", "query");
				map.put("permissionCode", "pending");
				break;
			case "b":
				map.put("module", "b");
				map.put("moduleCode", "myStartArchive");
				map.put("moduleName", "已归档");
				map.put("editType", "view");
				map.put("menuType", "my");
				map.put("permissionCode", "my");
				break;
			case "c":
				map.put("module", "c");
				map.put("moduleCode", "myStartNoArchive");
				map.put("moduleName", "待归档");
				map.put("editType", "view");
				map.put("menuType", "my");
				map.put("permissionCode", "my");
				break;
			case "d":
				map.put("module", "d");
				map.put("moduleCode", "dbfw");
				map.put("moduleName", "待办发文");
				map.put("editType", "edit");
				map.put("menuType", "pending");
				map.put("permissionCode", "pending");
				break;
			case "e":
				map.put("module", "e");
				map.put("moduleCode", "dbsw");
				map.put("moduleName", "待办收文");
				map.put("editType", "edit");
				map.put("menuType", "pending");
				map.put("permissionCode", "pending");
				break;
			default:
				break;
		}
	}

	/**
	 * 设置文件灯、个人灯   
	 * @Title: setLightType   
	 * @param info
	 * @author xuwl
	 * @date 2019-12-28 7:43:38 PM 
	 */ 
	@SuppressWarnings("all")
	private void setLightType(Map info,String module) {
		// 文件灯
		String preWarningDate = info.get("preWarningDate")+"";
		String warningDate = info.get("warningDate")+"";
		info.put("fileLight", "normallight");
		if(StringUtils.isNotEmpty(preWarningDate) && compareDate(preWarningDate)) {
			info.put("fileLight", "warnlight");
		}
		if(StringUtils.isNotEmpty(warningDate) && compareDate(warningDate)) {
			info.put("fileLight", "uragelight");
		}
		
		// 个人灯
		String taskPreWarningDate = info.get("taskPreWarningDate")+"";
		String taskWarningDate = info.get("taskWarningDate")+"";
		info.put("personLight", "normallight");
		if(StringUtils.isNotEmpty(taskPreWarningDate) && compareDate(taskPreWarningDate)) {
			info.put("personLight", "warnlight");
		}
		if(StringUtils.isNotEmpty(taskWarningDate) && compareDate(taskWarningDate)) {
			info.put("personLight", "uragelight");
		}
		// 已办处理
		if("2".equals(module)) {
			String dealTime = info.get("dealTime")+"";
			info.put("personLight", "normallight");
			if(StringUtils.isNotEmpty(taskPreWarningDate) && compareDate2(taskPreWarningDate,dealTime)) {
				info.put("personLight", "warnlight");
			}
			if(StringUtils.isNotEmpty(taskWarningDate) && compareDate2(taskWarningDate,dealTime)) {
				info.put("personLight", "uragelight");
			}
		}
	}
	
	private boolean compareDate(String finishStr) {
		if(finishStr.length() < 19) {
			return false;
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		try { 
			Date finishDate = format.parse(finishStr); 
			if(finishDate.before(new Date())) {
				return true;
			}
		} catch (Exception e) { 
			e.printStackTrace(); 
		} 
		return false;
	}
	
	private boolean compareDate2(String finishStr,String dealTimeStr) {
		if(finishStr.length() < 19) {
			return false;
		}
		if(dealTimeStr.length() < 19) {
			return false;
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		try { 
			Date finishDate = format.parse(finishStr); 
			Date dealTime = format.parse(dealTimeStr); 
			if(finishDate.before(dealTime)) {
				return true;
			}
		} catch (Exception e) { 
			e.printStackTrace(); 
		} 
		return false;
	}
	
	//判断日期是否是今天
    public boolean isToday(String timeStr) {
    	try {
    		Date time = sdf.parse(timeStr);
    		String param = sdf.format(time);//参数时间
    		String now = sdf.format(new Date());//当前时间
    		if (param.equals(now)) {
    			return true;
    		}
		} catch (Exception e) {
			e.printStackTrace();
		}
        return false;
    }
    
    //判断日期是否是昨天
    public boolean isYesterday(String timeStr) {
    	try {
    		Date time = sdf.parse(timeStr);
    		String param = sdf.format(time);//参数时间
    		Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            String yesterDay = sdf.format(calendar.getTime());
            if(param.equals(yesterDay)) {
            	return true;
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
        return false;
    }
 
    //判断日期是否是本周
    public boolean isThisWeek(String timeStr) {
        Calendar calendar = Calendar.getInstance();
        // 设置周一至周日为本周
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        int currentWeek = calendar.get(Calendar.WEEK_OF_YEAR);
        try {
        	Date time = sdf.parse(timeStr);
        	calendar.setTime(time);
		} catch (Exception e) {
			e.printStackTrace();
		}
        int paramWeek = calendar.get(Calendar.WEEK_OF_YEAR);
        if (paramWeek == currentWeek) {
            return true;
        }
        return false;
    }

    /**
   	 * 门户待阅、已阅接口
   	 * @Title: getListByPortlet   
   	 * @param menuType
   	 * @param limit
   	 * @author xuwl
   	 * @date 2019-11-22 9:20:24 PM
   	 */
   	public Map getListByPortletNum() {
   		WebUser user = WebUtils.getCurrentUser();
   		String corpId = user.getCorpId();
   		String userId = user.getUserId();
   		Map<String, Object> paramMap = new HashMap<String, Object>();
   		StringBuffer sql = new StringBuffer();
   		sql.append(" select count(*) num ");
   		sql.append(" from goa_doc_distribute_user t ");
   		sql.append(" inner join goa_doc_distribute_record b on t.dis_record_id = b.id left join act_hi_procinst ahp on b.business_id = ahp.business_key_ ");
   		sql.append(" where t.corp_id=:corpId ");
   		sql.append(" AND ( b.bln_delete = '0' OR b.bln_delete IS NULL )  ");
   		sql.append(" and t.receive_user_idstr = :userId ");
   		paramMap.put("userId",userId);
   		paramMap.put("corpId", corpId);
   		sql.append(" and t.status = '0' ");//待阅
   		//是否涉密开启
           Boolean secretFlag = GlobalConstant.isUseSecretLevel();
           if(secretFlag) {
           	//获取当前登录人的涉密登记
           	int secretLevel = user.getSecretLevel();
           	sql.append(" and (b.secretlevel >= '"+secretLevel + "' or b.secretlevel is null or b.secretlevel = '' ) ");
           }
   		//sql.append(" order by t.distribute_time desc");
   		List list = super.findByListNativeQuery(sql.toString(),"", paramMap);
   		Map map = new HashMap<>();
   		Map data = new HashMap<>();
   		String num = "0";
   		if(CollectionUtils.isNotEmpty(list) && list.size() == 1) {
   			Map maps = (Map) list.get(0);
   			num = StringUtils.null2String(maps.get("num"));
   		}
   		data.put("list", null);
   		data.put("count", num);
   		data.put("totalNum", num);
   		map.put("data", data);
   		map.put("code", 0);
   		return map;
   	}

   	/**
	 * 门户待阅、已阅接口
	 * @Title: getListByPortlet   
	 * @param menuType
	 * @param limit
	 * @author xuwl
	 * @date 2019-11-22 9:20:24 PM
	 */
	public Map getListByPortlet(String typeFlag,String menuType,String limit) {
		WebUser user = WebUtils.getCurrentUser();
		String corpId = user.getCorpId();
		String userId = user.getUserId();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append(" select t.id,dis_title as  dis_title, b.dis_user_name,b.dis_user_id,ahp.PROC_INST_ID_ as processInstanceId,ahp.EXT_URGENTFIELD as extUrgentField,ahp.EXT_STARTUSERGROUPNAME as startUserGroupName,b.dis_org_name,t.distribute_time createddate,t.read_status,t.form_id,t.business_id,t.process_id process_instance_id,t.task_id,t.file_real_ids,b.sendfile_no ");
		sql.append(" ,b.type doc_type,b.source_category category,t.dis_record_id ");
		sql.append(" ,t.is_confirm,t.sign_advice ");//是否需要已阅确认、是否进行确认是否必填
		sql.append(" ,t.dis_content_form,t.dis_content_file,t.dis_content_official,t.dis_content_endor,t.dis_content_enclosure,t.relation_flow,t.relation_record  ");//批示表单、正文、正式公文、全文签批单、附件
		sql.append(" ,re.createdDate finishdate,t.blnDownload,b.form_title  ");
		sql.append(" from goa_doc_distribute_user t ");
		sql.append(" inner join goa_doc_distribute_record b on t.dis_record_id = b.id ");
		sql.append(" LEFT join act_hi_procinst ahp on t.business_id = ahp.business_key_ ");
		sql.append(" left join goa_doc_distribute_return re on re.distribute_id =t.id and re.type='3' ");
		sql.append(" where t.corp_id=:corpId ");
		sql.append(" AND ( b.bln_delete = '0' OR b.bln_delete IS NULL )  ");
		sql.append(" and t.receive_user_idstr = :userId ");
		paramMap.put("userId", userId);
		paramMap.put("corpId", corpId);
		if("unread".equals(menuType)) {
			sql.append(" and t.status = '0' ");//待阅
		}else {
			sql.append(" and t.status = '1' ");//已阅
		}
		
		if("2".equals(typeFlag) ) {
			sql.append(" and b.type=:typeFlag");
			paramMap.put("typeFlag", 1);
		}else if("3".equals(typeFlag) ) {
			sql.append(" and b.type<>:typeFlag");
			paramMap.put("typeFlag", 1);
		}
		//是否涉密开启
        Boolean secretFlag = GlobalConstant.isUseSecretLevel();
        if(secretFlag) {
        	//获取当前登录人的涉密登记
        	int secretLevel = user.getSecretLevel();
        	sql.append(" and (b.secretlevel >= '"+secretLevel + "' or b.secretlevel is null or b.secretlevel = '' ) ");
        }
		sql.append(" order by createddate desc");
		//Pageable pageable = null;
    	//int offset = 0;
    	//int page = 0;
    	//int size = Integer.parseInt(ValidateUtils.filter(limit));
    	//pageable = new ExtPageRequest(offset, page, size, null);
    	//Page<Map> pageMap = this.findByPageNativeSQL(pageable, sql.toString(), paramMap);
    	//List<Map> newList = pageMap.getContent();
		List list = super.findByListNativeQuery(sql.toString(),"", paramMap);
		Integer num = 0;
		if(StringUtils.isNotEmpty(limit)) {
			 num = Integer.parseInt(limit);
		}
		if(num >= list.size()) {
			num = list.size();
		}
		List newList=list.subList(0, num);
//		newList = documentSecUtils.documentListEncodeListById(newList);
		newList = DocumentSecUtils.approveListEncodeList(newList,"processInstanceId","");
		Map map = new HashMap<>();
		Map data = new HashMap<>();
		//处理标题标签

		data.put("list", newList);
		data.put("count", newList.size());
		/*Map result = getListByPortletNum();
		if ("0".equals(StringUtils.null2String(result.get("code")))) {
			Map datas = (Map) result.get("data");
			data.put("totalNum", datas.get("totalNum"));
		}*/
		
		
		
		data.put("totalNum", list.size());
		map.put("data", data);
		map.put("code", 0);
		return map;
	}
	
	/**
	 * 门户我的分发
	 * @Title: getListByPortlet   
	 * @param map
	 * @author xuwl
	 * @date 2019-11-25 2:16:50 PM
	 */
	@SuppressWarnings("all")
	public Map getDisListByPortlet(String limit) {
		WebUser user = WebUtils.getCurrentUser();
		String corpId = user.getCorpId();
		String userId = user.getUserId();
		StringBuffer sql = new StringBuffer();
		sql.append(" select t1.id,t1.form_title as send_title,t1.type distype,t2.EXT_STARTUSERGROUPNAME as startUserGroupName,t2.EXT_URGENTFIELD as extUrgentField,t1.sendfile_no,t1.dis_date sendTime_selfsend, t1.business_id ,t1.form_id, ");
		sql.append(" t1.process_instance_id,t1.task_id,t1.source_category,t2.PROC_INST_ID_ as processInstanceId,t1.dis_content_form,t1.dis_content_file,t1.dis_content_official,t1.dis_content_endor,t1.dis_content_enclosure,t1.source, ");
		sql.append(" case when (t2.EXT_STARTUSERNAME is null or t2.EXT_STARTUSERNAME = '')  then t1.dis_user_name else t2.EXT_STARTUSERNAME end as starFlowtUser, ");
		sql.append(" case when (t2.EXT_STARTUSERGROUPNAME is null or t2.EXT_STARTUSERGROUPNAME = '') then t1.dis_org_name else t2.EXT_STARTUSERGROUPNAME end as starFlowtUnit ");
		sql.append(" from goa_doc_distribute_record t1 ");
		sql.append(" left join ACT_HI_PROCINST t2 on (t1.business_id=t2.BUSINESS_KEY_) ");
		sql.append(" where t1.dis_user_id=:userId AND ( t1.bln_delete = '0' OR t1.bln_delete IS NULL ) ");
		//是否涉密开启
        Boolean secretFlag = GlobalConstant.isUseSecretLevel();
        if(secretFlag) {
        	//获取当前登录人的涉密登记
        	int secretLevel = user.getSecretLevel();
        	sql.append(" and (t1.secretlevel >= '"+secretLevel + "' or t1.secretlevel is null or t1.secretlevel = '' ) ");
        }
		sql.append(" ORDER BY t1.dis_date desc ");
		Map paramMap = new HashMap();
		paramMap.put("userId", userId);		
        Pageable pageable = null;
    	int offset = 0;
    	int page = 0;
    	int size = Integer.parseInt(ValidateUtils.filter(limit));
    	pageable = new ExtPageRequest(offset, page, size, null);
    	Page<Map> pageMap = this.findByPageNativeSQL(pageable, sql.toString(), paramMap);
    	List<Map> newList = pageMap.getContent();
		newList = documentSecUtils.documentListEncodeListById(newList);
		/*List list = super.findByListNativeQuery(sql.toString(),"", paramMap);
		Integer num = Integer.parseInt(limit);
		if(num >= list.size()) {
			num = list.size();
		}
		List<Map> newList=list.subList(0, num);*/
		if(newList!=null&&newList.size()>0) {
			List<String> govIdsList = new ArrayList<String>(); 
			for (Map<String,Object> resultMap : newList) {
				 //分类
				 String id = (String) resultMap.get("business_id");
				 String recordId = (String) resultMap.get("id");
				 govIdsList.add(id);
				 
				 String PROC_INST_ID_ = resultMap.get("PROC_INST_ID_")==null?"":resultMap.get("PROC_INST_ID_").toString();
				 String source_category = resultMap.get("source_category")==null?"":resultMap.get("source_category").toString();
				/* String status_selfsend = "";
				 if(PROC_INST_ID_!=null&&!"".equals(PROC_INST_ID_)) {
					 status_selfsend = getStatus(PROC_INST_ID_);
				 }
				 if(status_selfsend==null||"".equals(status_selfsend)) {
					 status_selfsend = getFormStatus(source_category,id);
				 }
				 resultMap.put("status_selfsend", status_selfsend);*/
				 String file_real_ids = getFileReal(recordId);//获取接收人接收到的所有附件
				 resultMap.put("attachmentList", file_real_ids);
			 }
		}
//		newList = documentSecUtils.documentListEncodeListById(newList);
		newList = DocumentSecUtils.approveListEncodeList(newList,"processInstanceId","");
		Map map = new HashMap<>();
		Map data = new HashMap<>();
		data.put("list", newList);
		data.put("count", newList.size());
		map.put("data", data);
		map.put("code", 0);
		return map;
		
	}
	
	/**
	 * 根据record表的id获取所有的附件合集，用|隔开
	 * @param recordId
	 * @return
	 */
	private String getFileReal(String recordId) {
		String fileReal = "";
		StringBuffer sql = new StringBuffer();
		Map<String,Object> paramMap = new HashMap();
		
		sql.append(" select file_real_ids from goa_doc_distribute_user where dis_record_id = :recordId ");
		paramMap.put("recordId", recordId);
		List<Map> list = super.findByListNativeQuery(sql.toString(),"",paramMap);
		if(list!=null&&list.size()>0) {
			for(Map<String,Object> resultMap:list) {
				String file_real_ids = resultMap.get("file_real_ids")==null?"":resultMap.get("file_real_ids").toString();
				if(!"".equals(file_real_ids)) {
					if(fileReal.indexOf(file_real_ids)>-1) {
						continue;
					}
					if("".equals(fileReal)) {
						fileReal += file_real_ids;
					}else {
						fileReal += "|" + file_real_ids;
					}
				}
			}
		}
		
		return fileReal;
	}
	
	/**
	 * 我的关注数据-公文门户使用
	 * @param limit
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes", "unused" })
	public Map getMyAttentionListByPortlet(String limit) {
		//标题	发起人	发起单位	时间
		Map<String, Object> paramMap = new HashMap<String, Object>();
		WebUser user = WebUtils.getCurrentUser();
		StringBuffer sql = new StringBuffer();
		sql.append("select temp.* ");
		sql.append("from (");
		sql.append("select bpf.bln_delete,case ahp.ext_category when 'goa_doc_sendfile' then gds.title WHEN 'goa_doc_receivefile' THEN gdr.title ELSE gds2.title end as title,");
		sql.append("case ahp.ext_category when 'goa_doc_sendfile' then 'goa_doc_sendfile' WHEN 'goa_doc_receivefile' THEN 'goa_doc_receivefile' ELSE 'goa_doc_signreport' end as tableName,");
		sql.append("case ahp.ext_category when 'goa_doc_sendfile' then gds.security_classification WHEN 'goa_doc_receivefile' THEN gdr.security_classification ELSE gds2.security_classification end as securityClassification,");
		sql.append("case ahp.ext_category when 'goa_doc_sendfile' then gds.id WHEN 'goa_doc_receivefile' THEN gdr.id ELSE gds2.id end as tableId,");
		sql.append("case ahp.ext_category when 'goa_doc_sendfile' then gds.flow_status WHEN 'goa_doc_receivefile' THEN gdr.flow_status ELSE gds2.flow_status end as flowStatus,");
		sql.append("ahp.ext_startusername startUser,ahp.EXT_STARTUSERGROUPNAME AS startUnit, ahp.EXT_STARTUSERGROUPNAME as orgName,ahp.EXT_URGENTFIELD as extUrgentField,ahp.EXT_STARTUSERGROUPID as org_id,bpf.createdDate as attentionTime,ahp.START_TIME_ as startTime,ahp.ext_category as category,");
		sql.append("bpf.createdBy as attentionUser,bpf.follow_process_id as followProcessId,bpf.id,ahp.business_key_ as businessKey,ahp.ext_title as processTitle,ahp.EXT_PROCESSCODE processCode ");
		sql.append("from act_hi_procinst ahp ");
		sql.append("INNER JOIN bpm_process_followed bpf ON bpf.follow_process_id = ahp.PROC_INST_ID_  ");
		sql.append("left join goa_doc_sendfile gds on gds.id = ahp.business_key_   ");
		sql.append("left join goa_doc_receivefile gdr on gdr.id = ahp.business_key_   ");
		sql.append("left join goa_doc_signreport gds2 on gds2.id = ahp.business_key_   ");
		sql.append("where bpf.module = 'goa_document'");
		sql.append(" and (bpf.bln_delete ='0' or bpf.bln_delete is null) ");
		sql.append(") temp ");
		sql.append("where temp.tableId is not null and temp.tableId <> ' ' and (bln_delete ='0' or bln_delete is null) and temp.attentionUser = :userId");
		//是否涉密开启
        Boolean secretFlag = GlobalConstant.isUseSecretLevel();
        if(secretFlag) {
        	//获取当前登录人的涉密登记
        	int secretLevel = user.getSecretLevel();
        	sql.append(" and (temp.securityClassification >= '"+secretLevel + "' or temp.securityClassification is null or temp.securityClassification = '' ) ");
        }
		sql.append(" order by temp.attentionTime desc");
		paramMap.put("userId",user.getUserId());
        Pageable pageable = null;
    	int offset = 0;
    	int page = 0;
    	int size = Integer.parseInt(ValidateUtils.filter(limit));
    	pageable = new ExtPageRequest(offset, page, size, null);
    	Page<Map> pageMap = this.findByPageNativeSQL(pageable, sql.toString(), paramMap);
    	List<Map> newList = pageMap.getContent();

		if(newList.size() > 0 && newList != null) {
			List<String> businessKeyList = new ArrayList<String>();
		    List<Map> a = new ArrayList<Map>();
        	for (Map map2 : newList) {
    			String businessKey = (String) map2.get("tableId");
    			businessKeyList.add(businessKey);
    		}
        	String sql1 = " select aph.business_key_ ,su.user_name as dealUser,art.proc_def_id_,art.form_key_,aph.proc_inst_id_,art.id_,"+
        				  " art.name_ as dealName,pro.name_  " + 
    	       		      " from ACT_HI_PROCINST aph " +
    	       		      " left join ACT_RU_TASK art on art.PROC_INST_ID_ = aph.PROC_INST_ID_  "+
    	       		      " left join sys_user su on su.id = art.ASSIGNEE_ "+ 
    	       		      " left join act_re_procdef pro on aph.proc_def_id_ = pro.id_ where aph.business_key_ in(:busniesskey)";
        	Map paramMap1 = new HashMap();
        	paramMap1.put("busniesskey", businessKeyList);
        	a = super.findByListNativeQuery(sql1.toString(), "",paramMap1);
        	
        	for (int j = 0; j < newList.size(); j++) {
        		Map  listmap = newList.get(j);
        		String id = (String) newList.get(j).get("tableId");
        		String alldealUser  = "";
        		String proc_def_id_="";
        		String form_key_="";
        		String proc_inst_id_="";
        		String id_="";
        		String dealStatus="";
        		for (int L = 0; L < a.size(); L++) {
        			String businesskey = (String) a.get(L).get("business_key_");
        			String dealUser = a.get(L).get("dealUser") == null ? "" : (String) a.get(L).get("dealUser");
        			if(id.equals(businesskey)) {
        				alldealUser += dealUser+",";
        				proc_def_id_ = (String) a.get(L).get("proc_def_id_");
        				form_key_ = (String) a.get(L).get("form_key_");
        				proc_inst_id_ = (String) a.get(L).get("proc_inst_id_");
        				id_ = (String) a.get(L).get("id_");
        				dealStatus = (String) a.get(L).get("dealName");
        			}
        		}
        		if(StringUtils.isNotBlank(alldealUser) && alldealUser.length()>0) {
        			alldealUser = alldealUser.substring(0,alldealUser.length()-1);
        		}
        		listmap.put("dealUser", alldealUser);
        		listmap.put("proc_def_id_",  proc_def_id_);
        		listmap.put("form_key_", form_key_);
        		listmap.put("proc_inst_id_", proc_inst_id_);
				listmap.put("processInstanceId", proc_inst_id_);
				listmap.put("id_", id_);
        		if(StringUtils.isEmpty(dealStatus)) {
        			dealStatus = "结束";
        		}
        		listmap.put("dealStatus", dealStatus);
        	}
        }
		Map map = new HashMap<>();
		Map data = new HashMap<>();
		newList = documentSecUtils.documentListEncodeListById(newList);
		newList = DocumentSecUtils.approveListEncodeList(newList,"processInstanceId","");
		data.put("list", newList);
		data.put("count", newList.size());
		map.put("data", data);
		map.put("code", 0);
		return map;
	}
	
	/**
	 * 公文办理列表-我的退回门户列表
	 * @param limit
	 * @return
	 */
	public Map getFlowBackListByPortlet(String limit) {
		WebUser user = WebUtils.getCurrentUser();
		//String corpId = user.getCorpId();
		String userId = user.getUserId();
		StringBuffer sql = new StringBuffer();
		Map<String,Object> paramMap = new HashMap<String, Object>();
		sql.append(" select (case when t2.ext_title  is not null then ext_title else t1.title end) as title,t1.back_user backUser,t1.back_act backAct,t1.back_time backTime,t3.NAME_ dealstatus,t1.back_reason backReason,t1.flow_type,t1.business_key business_id, "
				+ "t1.business_key businessKey,t2.EXT_STARTUSERGROUPNAME as startUserGroupName, t2.PROC_INST_ID_ as processInstanceId, t2.EXT_URGENTFIELD as extUrgentField,t1.form_id formKey,t1.task_id,t1.process_instance_id,t2.ext_startusername,t2.ext_startusergroupname ");
		sql.append(" from goa_flow_back t1 ");
		sql.append(" left join ACT_HI_PROCINST t2 on (t1.business_key = t2.BUSINESS_KEY_)  ");
		sql.append(" left JOIN ACT_RU_TASK t3 on (t2.PROC_INST_ID_ = t3.PROC_INST_ID_) ");
		sql.append(" where (t1.bln_delete = '0' or t1.bln_delete is null)  and t1.createdBy = :userId ");
		
		
		//是否涉密开启
        Boolean secretFlag = GlobalConstant.isUseSecretLevel();
        if(secretFlag) {
        	//获取当前登录人的涉密登记
        	int secretLevel = user.getSecretLevel();
        	sql.append(" and (t1.secretlevel >= '"+secretLevel + "' or t1.secretlevel is null or t1.secretlevel = '' ) ");
        }
		sql.append(" ORDER BY t1.createdDate desc ");
		paramMap.put("userId", userId);
        Pageable pageable = null;
    	int offset = 0;
    	int page = 0;
    	int size = Integer.parseInt(ValidateUtils.filter(limit));
    	pageable = new ExtPageRequest(offset, page, size, null);
    	Page<Map> pageMap = this.findByPageNativeSQL(pageable, sql.toString(), paramMap);
    	List<Map> newList = pageMap.getContent();
//		newList = documentListEncodeListByKey(newList);

		if(newList!=null&&newList.size()>0) {
			for (Map<String,Object> resultMap : newList) {
				 //分类
				 String id = (String) resultMap.get("business_id");
				 String flow_type = (String) resultMap.get("flow_type");
				 String proc_inst_id_ = (String) resultMap.get("processInstanceId");
				 String dealstatus = resultMap.get("dealstatus")==null?"":resultMap.get("dealstatus").toString();
				 if(dealstatus==null||"".equals(dealstatus)) {
					 String source_category = "";
					 if("0".equals(flow_type)){
						 source_category="goa_doc_sendfile";
					 }else if("1".equals(flow_type)){
						 source_category="goa_doc_receivefile";
					 }else if("2".equals(flow_type)){
						 source_category="goa_doc_signreport";
					 }
					 String realDealStatus = disRecordService.getFormStatus(source_category,id);
					 resultMap.put("dealstatus", realDealStatus);
				 }
				resultMap.put("processInstanceId", proc_inst_id_);
			 }
		}
		Map map = new HashMap<>();
		Map data = new HashMap<>();
		newList = DocumentSecUtils.approveListEncodeList(newList,"processInstanceId","");
		data.put("list", newList);
		data.put("count", newList.size());
		map.put("data", data);
		map.put("code", 0);
		return map;
		
	}

	/**
	 * 门户待阅收文、待阅阅文接口
	 * @Title: getListByPortlet
	 * @param menuType
	 * @param limit
	 */
	public Map getDocWaitingReadFileRecv(String typeFlag,String menuType,String limit) {
		WebUser user = WebUtils.getCurrentUser();
		String corpId = user.getCorpId();
		String userId = user.getUserId();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append(" select t.id,dis_title as  title, b.dis_user_name startUserName,ahp.PROC_INST_ID_ as processInstanceId,ahp.EXT_URGENTFIELD as extUrgentField,ahp.EXT_STARTUSERGROUPNAME as startUserGroupName,b.dis_user_id,t.distribute_time createTime,t.read_status,t.form_id as formKey,t.business_id as businessKey,t.process_id process_instance_id,t.task_id,t.file_real_ids,b.sendfile_no ");
		sql.append(" ,b.type doc_type,b.source_category category,t.dis_record_id ");
		sql.append(" ,t.is_confirm,t.sign_advice ");
		sql.append(" ,t.dis_content_form,t.dis_content_file,t.dis_content_official,t.dis_content_endor,t.dis_content_enclosure  ");//批示表单、正文、正式公文、全文签批单、附件
		sql.append(" ,re.createdDate finishdate,t.blnDownload,b.form_title  ");
		sql.append(" from goa_doc_distribute_user t ");
		sql.append(" inner join goa_doc_distribute_record b on t.dis_record_id = b.id ");
		sql.append(" LEFT join act_hi_procinst ahp on t.business_id = ahp.business_key_ ");
		sql.append(" left join goa_doc_distribute_return re on re.distribute_id =t.id and re.type='3' ");
		sql.append(" where t.corp_id=:corpId ");
		sql.append(" AND ( b.bln_delete = '0' OR b.bln_delete IS NULL )  ");
		sql.append(" and t.receive_user_idstr = :userId and t.status = '0' ");
		paramMap.put("userId", userId);
		paramMap.put("corpId", corpId);

		//typeFlag:2-收文，3-阅文
		if("2".equals(typeFlag) ) {
			sql.append(" and b.type=:typeFlag");
			paramMap.put("typeFlag", 1);
		}else if("3".equals(typeFlag) ) {
			sql.append(" and b.type<>:typeFlag");
			paramMap.put("typeFlag", 1);
		}
		//是否涉密开启
		Boolean secretFlag = GlobalConstant.isUseSecretLevel();
		if(secretFlag) {
			//获取当前登录人的涉密登记
			int secretLevel = user.getSecretLevel();
			sql.append(" and (b.secretlevel >= '"+secretLevel + "' or b.secretlevel is null or b.secretlevel = '' ) ");
		}
		sql.append(" order by createTime desc");
		List list = super.findByListNativeQuery(sql.toString(),"", paramMap);
		Integer num = Integer.parseInt(limit);
		if(num >= list.size()) {
			num = list.size();
		}
		List newList=list.subList(0, num);
//		newList = documentSecUtils.documentListEncodeListById(newList);
		newList = DocumentSecUtils.approveListEncodeList(newList,"processInstanceId","");
		Map map = new HashMap<>();
		Map data = new HashMap<>();
		data.put("list", newList);
		data.put("count", newList.size());
		data.put("totalNum", list.size());
		map.put("data", data);
		map.put("code", 0);
		return map;
	}
	/**
	 * 门户我的发起-已归档-1、待归档-0
	 * @Title: getMyStartArchive
	 * @param map
	 */
	public Map getArchive(String typeFlag,String limit) {
		WebUser user = WebUtils.getCurrentUser();
		String corpId = user.getCorpId();
		String userId = user.getUserId();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		StringBuffer sql = new StringBuffer();
		sql.append("  SELECT aht.id_ as id,aht.FORM_KEY_ as formKey, RES.PROC_INST_ID_ as processInstanceId,RES.BUSINESS_KEY_ as businessKey,RES.EXT_CATEGORY as category,RES.EXT_TITLE AS title,RES.START_TIME_ as createTime,RES.EXT_URGENTFIELD as extUrgentField, RES.EXT_STARTUSERGROUPNAME AS startUserGroupName,EXT_STARTUSERNAME as startUserName,RES.EXT_MODULE, bpa.archive_status as  archiveStatus  FROM ACT_HI_PROCINST RES ");
		sql.append(" LEFT JOIN bpm_process_archive bpa on bpa.process_instance_id=RES.PROC_INST_ID_ ");
		sql.append(" LEFT JOIN act_hi_taskinst aht on aht.proc_inst_id_=RES.PROC_INST_ID_  and aht.name_ = '发起人' ");
		sql.append(" WHERE 1= 1  and RES.EXT_MODULE =  'goa_document'  AND RES.START_USER_ID_ = :userId ");
		sql.append(" AND RES.TENANT_ID_ = :corpId  AND RES.EXT_PROCESSSTATUS != '-1' and RES.EXT_PROCESSSTATUS != '0' ");
		sql.append(" and RES.ext_processstatus!='5'  AND (RES.DELETE_REASON_ is null or RES.DELETE_REASON_ != 'delete myprocess') ");
		paramMap.put("userId", userId);
		paramMap.put("corpId", corpId);

		//typeFlag:1-已归档，0-待归档
		if("1".equals(typeFlag) ) {
			sql.append(" and bpa.archive_status = '1'  ");
		}else if("0".equals(typeFlag) ) {
			sql.append(" and (bpa.archive_status = '0' or bpa.archive_status is null or bpa.archive_status='')  ");
		}
		sql.append(" ORDER BY  RES.START_TIME_ DESC ");
		List list = super.findByListNativeQuery(sql.toString(),"", paramMap);
		Integer num = Integer.parseInt(limit);
		if(num >= list.size()) {
			num = list.size();
		}
		List newList=list.subList(0, num);
//		newList = documentSecUtils.documentListEncodeListById(newList);
		newList = DocumentSecUtils.approveListEncodeList(newList,"processInstanceId","");
		Map map = new HashMap<>();
		Map data = new HashMap<>();
		data.put("list", newList);
		data.put("count", newList.size());
		data.put("totalNum", list.size());
		map.put("data", data);
		map.put("code", 0);
		return map;
	}
	/**
	 * 门户-收文登记未处理
	 * @Title: getListByPortlet
	 * @param map
	 */
	@SuppressWarnings("all")
	public Map getRegisterByPortlet(String limit) {
		WebUser user = WebUtils.getCurrentUser();
		StringBuffer sql = new StringBuffer();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		sql.append(" select pm.id as businessKey,pm.serial_number serialNumber,pm.register_number registerNumber, pm.title,pm.communication_number communicationNumber,pm.communication_dept communicationDept,pm.communication_time createTime,pm.register_user startUserName,pm.handing_status handingStatus,pm.security_classification securityClassification,");
		sql.append(" go.unitname startUserGroupName,emm.name as securityClass,emr.name emergencyAgency,pm.file_type fileType,pm.sort_no sortNo,pm.corp_id,pm.isDelete,pm.createdDate,pm.createdOrg,pm.createdBy,pm.formid as formKey,(select count(*)  from goa_document_attachment so where so.document_id = pm.id and so.isDelete = 0 and so.document_source = 4 and so.file_source <> 4) filenum ");
		sql.append(" from goa_doc_register pm ");
		sql.append(" left join goa_receivefile_receiveorg go on go.id = pm.communication_dept ");
		sql.append(" left join sys_dict_detail emr   on emr.code = pm.emergency_agency  and emr.cate_id = '6841833782df11ea847400505683e8cd'  ");
		sql.append(" left join sys_dict_detail emm   on emm.code = pm.security_classification  and emm.cate_id = 'c2618ded23a411ea847400505683e8cd'  ");
		sql.append(" where  (pm.isDelete is null or pm.isDelete = 0) and pm.handing_status is null ");
		sql.append("  order by pm.sort_no,pm.communication_time desc ");
		List list = super.findByListNativeQuery(sql.toString(),"", paramMap);
		Integer num = Integer.parseInt(limit);
		if(num >= list.size()) {
			num = list.size();
		}
		List newList=list.subList(0, num);
		newList = documentListEncodeListByKey(newList);
//		newList = DocumentSecUtils.approveListEncodeList(newList,"processInstanceId","");
		Map map = new HashMap<>();
		Map data = new HashMap<>();
		data.put("list", newList);
		data.put("count", newList.size());
		data.put("totalNum", list.size());
		map.put("data", data);
		map.put("code", 0);

		return map;

	}

	private static final String moduleCode1 = "goa_document";
	//应用分类--列表页面数据加密字段
	public static final String AC_PAGE_FIELD_BUID = "businessKey";
//	public static final String AC_PAGE_FIELD_IDUSERID = "businessKey,userId";

	/**
	 * 应用分类列表页面数据字段加密
	 *
	 * @param list 查询的列表数据list
	 * @return
	 */
	public static List<Map> documentListEncodeListByKey(List<Map> list){
		if(list!=null && list.size()>0) {
			list = DealFieldEncodeUtils.dealDataList(list,AC_PAGE_FIELD_BUID, moduleCode1, null);
		}
		return list;
	}
}
